#include "stdafx.h"
#include "LogFile.h"
#include "config.h"

#include "windows.h"

#include <sstream>


LogFile *LogFile::Instance = 0;

LogFile::LogFile() {
	IsOpen = false;
}


LogFile::~LogFile() {
	if(IsOpen) {
		fclose(Output);
		IsOpen = false;
	}
}

bool LogFile::Create() {
	if(Instance == 0) {
		Instance = new LogFile();

		Config *cfg = Config::getInstance();
		string name = cfg->getValue("AdaptorLogFile", "Adaptor");
		UpdateTime();
		char fileName[256];
		char date[32];
		sprintf(date, "%04d-%02d-%02d", Instance->SysTime.wYear, Instance->SysTime.wMonth, Instance->SysTime.wDay);
		sprintf(fileName, "%s.%s.log", name.c_str(), date);
		Instance->Output = fopen(fileName, "a");
		if( Instance->Output ) {
			Instance->IsOpen = true;
		} else {
			delete Instance;
			Instance = 0;
			return false;
		}
		stringstream ss;
		ss << "Log opened on " << date;
		PrintLine(ss.str());

		return true;
	} else {
		return true;
	}
}

void LogFile::PrintLine(const string & ss, bool updateTime) {
	if( Instance ) {
		if(updateTime) UpdateTime();
		SYSTEMTIME *time = &Instance->SysTime;
		fprintf(Instance->Output, "%02d:%02d:%02d.%03d %s\n", 
			time->wHour, time->wMinute, time->wSecond, 
			time->wMilliseconds, ss.c_str());
	}
}

void LogFile::Print(bool updateTime, const char* format, ...) {
	if (Instance) {
		if(updateTime) UpdateTime();
		SYSTEMTIME *time = &Instance->SysTime;
		fprintf(Instance->Output, "%02d:%02d:%02d.%03d ", time->wHour, time->wMinute, time->wSecond, 
			time->wMilliseconds);
		va_list argptr;
		va_start(argptr, format);
		vfprintf(Instance->Output, format, argptr);
		va_end(argptr);
	}
}

void LogFile::UpdateTime() {
	if(Instance) {
		GetSystemTime(&Instance->SysTime);
	}
}
